import { Request, Response, NextFunction } from 'express';
import { verifyToken } from '@/config/jwt';
import { User } from '@/models/User';

export interface AuthenticatedRequest extends Request {
  user?: any;
  userId?: string;
}

export const authenticate = async (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const authHeader = req.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      res.status(401).json({
        success: false,
        message: '访问令牌是必需的',
      });
      return;
    }

    const token = authHeader.substring(7);
    const decoded = verifyToken(token);

    // 验证用户是否存在
    const user = await User.findById(decoded.userId);
    if (!user) {
      res.status(401).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    req.user = user;
    req.userId = decoded.userId;
    next();
  } catch (error) {
    res.status(401).json({
      success: false,
      message: '无效的访问令牌',
    });
  }
};

export const requireRole = (requiredRole: string) => {
  return (
    req: AuthenticatedRequest,
    res: Response,
    next: NextFunction
  ): void => {
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '需要身份验证',
      });
      return;
    }

    if (req.user.role !== requiredRole) {
      res.status(403).json({
        success: false,
        message: '权限不足',
      });
      return;
    }

    next();
  };
};

export const requireAnyRole = (roles: string[]) => {
  return (
    req: AuthenticatedRequest,
    res: Response,
    next: NextFunction
  ): void => {
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '需要身份验证',
      });
      return;
    }

    if (!roles.includes(req.user.role)) {
      res.status(403).json({
        success: false,
        message: '权限不足',
      });
      return;
    }

    next();
  };
};
